<?php

namespace App\Kuafu\Shop\Controller\Merchant;

use App\Exceptions\BaseException;
use App\Kuafu\Base\Controller\BaseController;
use App\Kuafu\Base\Model\BaseModel;
use App\Kuafu\Common\Enum\CodeEnum;
use App\Kuafu\Common\Service\CommonService;
use App\Kuafu\Shop\Enum\ShopCodeEnum;
use App\Kuafu\Shop\Exceptions\ShopException;
use App\Kuafu\Shop\Model\CollectShopListModel;
use App\Kuafu\Shop\Model\Shop;
use App\Kuafu\Shop\Service\ShopArchivesService;
use App\Kuafu\Shop\Service\ShopService;
use App\Kuafu\Shop\Validate\ShopValidate;
use App\Kuafu\User\Enum\RoleCodeEnum;
use App\Kuafu\User\Exceptions\AuthException;
use App\Kuafu\User\Exceptions\UserException;
use App\Kuafu\User\Service\AuthService;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ShopController extends BaseController
{
    /*
     *  获取门店列表
     */
    public function getShopList(Request $request): JsonResponse
    {
        $userId = AuthService::getUserId();
        $valid  = ShopValidate::getShopList(['userId' => $userId]);
        if ($valid) {
            return $this->fail(ShopCodeEnum::ERR_SHOP_INPUT, $valid);
        }

        return $this->success([
            'lists' => ShopService::userShopLists($userId),
        ]);
    }

    /**
     * 设置运营目标
     * @param Request $request
     * @return JsonResponse
     * @throws ShopException
     */
    public function setShopOperate(Request $request): JsonResponse
    {
        $valid = ShopValidate::setShopTarget($request);
        if ($valid) {
            return $this->fail(ShopCodeEnum::ERR_SHOP_INSERT, $valid);
        }
        ShopService::addShopTarget($request->shopId, $request->target, $request->header('brandId'));
        return $this->success();
    }

    /**
     * 获取门店配置
     * @param Request $request
     * @return JsonResponse
     * @throws ShopException
     */
    public function getShopInfo(Request $request)
    {
        $shopInfo                        = ShopService::getShopInfo($this->shopId)->toArray();
        $shopBusinessTimeChangeByDb      = ShopService::getShopBusinessTimeChangeByDb($shopInfo['startAt'],
            $shopInfo['endAt']);
        $shopInfo['formatStartAt']       = $shopBusinessTimeChangeByDb['startAt'];
        $shopInfo['formatEndAt']         = $shopBusinessTimeChangeByDb['endAt'];
        $shopInfo['archives']            = ShopArchivesService::getArchivesInfo($this->shopId);
        $shopInfo['introducerSelection'] = collect(Shop::INTRODUCER_TEXT)->map(function ($val, $key) {
            return array_merge($val, ["val" => $key]);
        })->values()->toArray();
        return $this->success($shopInfo);
    }

    /**
     * 设置门店配置
     * @param Request $request
     * @return JsonResponse
     * @throws ShopException
     */
    public function setShopConfig(Request $request)
    {
        $isBusiness   = (int)$request->isBusiness ?: \App\Kuafu\Shop\Enum\CodeEnum::SHOP_BUSINESS_STATUS_SUSPEND;
        $appletStatus = (int)$request->appletStatus ?: \App\Kuafu\Shop\Enum\CodeEnum::SHOP_APPLET_STATUS_NORMAL;
        $mobile       = (string)$request->shopMobile ?: "";
        // 开启是否门店自配送
        $isOpenSelfDelivery = $request->archives['isOpenSelfDelivery'] ?? 0;

        // 判断是否传了
        if (empty($request->get('startAt'))) {
            $timeChange = [];
        } else {
            $timeChange = ShopService::shopBusinessTimeChange($request->startAt, $request->endAt);
        }

        if ($mobile && !preg_match('/^1\d{10}$/', $mobile)) {
            return $this->fail(ShopCodeEnum::ERR_SHOP_MOBILE, '手机号格式错误');
        }

        if ($appletStatus == \App\Kuafu\Shop\Enum\CodeEnum::SHOP_APPLET_STATUS_SUSPEND) {
            $isOpenSelfDelivery = BaseModel::SWITCH_OFF;
        }

        $shopArchives = [
            'wechat'               => $request->archives['wechat'] ?? '',
            'wechatUrl'            => $request->archives['wechatUrl'] ?? '',
            'wechatPic'            => $request->archives['wechatPic'] ?? '',
            'eWechat'              => $request->archives['eWechat'] ?? '',
            'eWechatUrl'           => $request->archives['eWechatUrl'] ?? '',
            'eWechatPic'           => $request->archives['eWechatPic'] ?? '',
            'minSelfDeliveryPrice' => $request->archives['minSelfDeliveryPrice'] ?? 0,
            'selfDeliveryNotice'   => $request->archives['selfDeliveryNotice'] ?? '',
            'isOpenSelfDelivery'   => $isOpenSelfDelivery
        ];

        $updateData = [
            'shopContact'          => $request->get('shopContact', ''),
            "dyCouponVerifySwitch" => $request->get('dyCouponVerifySwitch', 0),
            "introducer"           => $request->get('introducer', 1),
        ];
        $shopId     = ShopService::setShopConfigInfo(
            $this->shopId,
            $isBusiness,
            $appletStatus,
            $timeChange,
            $mobile,
            $shopArchives,
            $updateData
        );
        return $this->success(['shopId' => $shopId]);
    }

    /**
     * 获取门店下员工列表
     * @param Request $request
     * @return JsonResponse
     */
    public function getShopStaffList(Request $request): JsonResponse
    {
        $valid = ShopValidate::useShopStatus($request);
        if ($valid) {
            return $this->fail(ShopCodeEnum::ERR_SHOP_INPUT, $valid);
        }
        $result = ShopService::getShopStaffInfo($this->shopId, (int)$request->status);
        return $this->success($result);
    }

    /**
     * 获取门店下员工详情
     * @param Request $request
     * @return JsonResponse
     */
    public function getUserDetail(Request $request): JsonResponse
    {
        $valid = ShopValidate::getUserDetail($request->all());
        if ($valid) {
            return $this->fail(ShopCodeEnum::ERR_SHOP_INPUT, $valid);
        }

        $userId = (int)$request->userId;

        $info = ShopService::getUserDetail($userId, $this->shopId);

        return $this->success($info);
    }

    /**
     * 获取门店职位
     * @param Request $request
     * @return JsonResponse
     */
    public function getShopPositions(Request $request)
    {
        $type = (int)$request->get("type", RoleCodeEnum::ROLE_BUSINESS_TYPE);
        if (!in_array($type, array_keys(RoleCodeEnum::ROLE_TYPE_LIST))) {
            return $this->fail(ShopCodeEnum::ERR_SHOP_INPUT, "类型输入有误");
        }
        $info = ShopService::getShopPositions((int)$request->header('shopId'), (int)$request->header('brandId'), $type);

        return $this->success($info);
    }

    /**
     * 获取门店运营目标详情
     * @param Request $request
     * @return JsonResponse
     * @throws UserException
     */
    public function getShopOperateDetail(Request $request)
    {
        $operateDetail = ShopService::getShopOperateDetail((int)$request->shopId, (int)$request->header('brandId'));

        return $this->success($operateDetail);
    }

    public function isCollectShop(Request $request)
    {
        //是否收藏门店
        $userId    = AuthService::getUserId();
        $shopId    = (int)$request->post('shopId', 0);
        $isCollect = (int)$request->post('collect', 0);
        ShopService::isCollectShop($shopId, $isCollect, $userId);
        return $this->success();
    }


    /**
     * @param Request $request
     * @return JsonResponse
     * @throws UserException
     * @throws BaseException
     * @throws AuthException
     */
    public function shopList(Request $request): JsonResponse
    {
        $name        = (string)$request->get("name", "");
        $page        = (int)$request->get('page', 1);
        $pageSize    = (int)$request->get('pageSize', 10);
        $payload     = AuthService::getPayload()->toArray();
        $isStaff     = isset($payload["thirdLoginType"]) && $payload["thirdLoginType"];
        $isCollected = (int)$request->get("isCollected", 0);
        $status      = (int)$request->get('status', -1);
        $shopId      = (int)$request->get('shopId', 0);

        $whereCondition = [
            'status' => $status
        ];
        return $this->success(ShopService::appShopList(
            AuthService::getUserId(),
            $isStaff,
            $name,
            $shopId,
            $isCollected,
            $page,
            $pageSize,
            [], $whereCondition
        ));
    }
}
